# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
import jinja2
import logging
import json
import time
import datetime
from wechatpy import WeChatClient
from wechatpy.client.api import WeChatJSAPI
import hashlib
from odoo import tools, _

from odoo.addons.web.controllers.main import DataSet

_logger = logging.getLogger(__name__)

loader = jinja2.PackageLoader('odoo.addons.lift_main', "views/jinja")

env = jinja2.Environment(loader=loader, autoescape=True)
env.filters["json"] = json.dumps

# jinja过滤器 下次维保时间比上次维保时间+15天
def adddays(val,num=15):
    if not val:
        return ""
    return (datetime.datetime.strptime(val,'%Y-%m-%d')+datetime.timedelta(days = num)).strftime('%Y-%m-%d')

env.filters['adddays'] = adddays

class BindLift(http.Controller):
    @http.route("/lift/detail/<string:code>", auth="public", type="http")
    def public_lift_detail(self, code, **kw):
        """
        首先方法针对大卡二维码，大卡是二维码跳转地址，小卡只有芯片卡号，扫小卡是进不来这个方法的
        微信公众号因为是统一配置，所以默认为code=nocode,所以后续不能依赖于这个值，页面上是重新扫码获得芯片号的
        简化后，不考虑牌子的更换操作，更换提交后台申请，所以已经有的值就不能重新绑定
        基于上面的原因，电梯也不能在这个绑定操作中更换维保单位，默认前提是进入系统的电梯就已经有维保单位了
        该方法提供几种支持
        增加：前提是默认公众扫码的时候电梯已经是完全绑定状态，绑定完全则进入详情页面，进绑定页面之前要判断登录
        1 第一次发现没有相应电梯，进入绑定操作页面(需要微信JSDK)--+判断登录
        2 电梯已经绑定，部位尚未绑定全,进入电梯详情页面(不需要微信JSDK)
        3 大众扫码跳转到电梯详细页面（不需要微信JSDK）
        部位卡不是一次绑定的，然后只要标识牌绑了就能进详情页面，在详情页面添加绑定按钮
            --由于无法识别未登陆的维保人员，所以只要没绑定全的，都显示按钮
        :param code: 电梯编号
        :param kw:
        :return: html
        """
        error_msg = u"没有电梯编号!"
        if code:
            lift_record = request.env["tyibs.base.lift"].sudo().search([("code", "=", code)], limit=1)
            public_notice = request.env["tyibs.base.public.notice"].sudo().search([], order="send_time desc", limit=1)
            if lift_record:
                # 情况 2 或 3，继续判断该电梯下---1 没有部位 2 有部位，且存在没有编号的部位 3 有部位，且都有编号
                if lift_record.lift_part_ids:
                    unbind_part = request.env["tyibs.main.lift.part"].sudo().search([("lift_id", "=", lift_record.id),('qrcode','=',False)])
                    if len(unbind_part)>0:
                        # 有部位未绑定 --- 情况2-尚未完成绑定任务
                        # 直接跳详细页面:有绑定按钮
                        return env.get_template("public_lift_detail.html").render({'lift': lift_record,'has_bind':'no','code':code, 'notice': public_notice})
                    else:
                        # 部位都绑定过了 --- 情况3-大众扫码
                        return env.get_template("public_lift_detail.html").render({'lift': lift_record, 'notice': public_notice})
                else:
                    # 没有部位 --- 情况3-大众扫码
                    return env.get_template("public_lift_detail.html").render({'lift': lift_record, 'notice': public_notice})
            else:
                # 情况1 该芯片卡号没有绑定电梯
                if self.if_login():
                    return env.get_template("public_bind_lift.html").render({'errcode':'01','haslift':'no'})
                else:
                    return env.get_template("public_login.html").render({'errcode':'01'})
        else:
            # 参数错误
            return env.get_template("error.html").render({'error_msg': error_msg})

    @http.route('/main/lift/detail/<string:code>',auth="public", type="http")
    def continuBind(self,code):
        """公众号电梯详情页面继续给电梯部位绑定的按钮"""
        if self.if_login():
            return env.get_template("public_bind_lift.html").render({'errcode':'02','code':code,'haslift':'yes'})
        else:
            return env.get_template("public_login.html").render({'errcode':'01'})

    def if_login(self):
        """ 此方法是供后台方法查询是否登录用户 """
        return True if request.session.uid else False
    
    @http.route('/mainiflogin', auth='public')
    def iflogin(self, **kw):
        """
        首先判断存不存在session：此方法是供前端js判断是否登录用，和if_login不合并：返回参数给前端和给后端的格式比较难统一
        """
        code = request.session['uid']
        if request.session['uid']:
            user_id = request.env["res.users"].sudo().search([("id", "=", request.session['uid'])], limit=1)
            # 维保人员获取员工ID
            main_employee_id = request.env["tyibs.base.maintenance.company.employee"].sudo().search([("res_user_id", "=", request.session['uid'])], limit=1)
            return json.dumps({
                'err':0,
                'uid':code,
                'uname':user_id.name,
                'user_type':user_id.user_type,
                'use_company_id':user_id.use_company_id.id,
                'maintenance_company_id':user_id.main_company_id.id,
                'main_employee_id':main_employee_id.id,
                'qs_company_id':user_id.qs_company_id.id,
                'check_company_id':user_id.check_company_id.id
                })
        else:
            return json.dumps({'err': 1})

    @http.route('/mainlogin', auth='public')
    def mainlogin(self, **kw):
        """ 把登录信息写进session """
        user_id = request.env["res.users"].sudo().search([("login", "=", kw['login'])], limit=1)
        if len(user_id)==0:
            return json.dumps({'err': 1})
        request.session['uid'] = user_id.id
        request.session['login'] = kw['login']
        request.session['password'] = kw['password']
        return json.dumps({'err': 0})


    @http.route("/main/lift/public/search", auth="user")
    def public_lift_search(self, **kw):
        """
        公众号绑定页面搜索电梯列表
        """
        # zrtodo:权限功能上线后把sudo去掉
        lift_records = request.env["tyibs.base.lift"].sudo().search(
            ['|',('code','ilike',kw['searchname']),
            '|',('use_company_id','ilike',kw['searchname']),
            '|',('use_address','ilike',kw['searchname']),
            '|',("register_code", "ilike", kw['searchname']),('factory_number','ilike',kw['searchname'])], limit=50)
        lift_list=[]
        for lift in lift_records:
            lift_list.append({
                'id':lift.id,
                'code':lift.code,
                'register_code':lift.register_code,
                'factory_number':lift.factory_number,
                'use_company_id':lift.use_company_id.name,
                'use_address':lift.use_address
            })
        return json.dumps({"lift_list":lift_list})

    @http.route("/main/lift/public/info/<string:lift_id>", auth="user")
    def public_lift_info(self,lift_id):
        """
        公众号绑定页面搜索电梯详情
        """
        lift = request.env["tyibs.base.lift"].sudo().search([("id", "=", lift_id)], limit=1)
        lift_info = {
            "id":lift.id,
            'register_code':lift.register_code,
            'factory_number':lift.factory_number,
            'use_company_id':lift.use_company_id.name,
            'use_address':lift.use_address,
            'maintenance_company_name':lift.maintenance_company_id.name,
            'maintenance_company_id':lift.maintenance_company_id.id,
            'rfid_code':lift.rfid_code,
            'code':lift.code,
            'gps_address':lift.gps_address,
            'ln':lift.ln,
            'la':lift.la,
            'line_operator_ids':[{'id':item.id,'name':item.name} for item in lift.line_operator_ids],
            'bind_image':'1' if lift.bind_image else '',
            'lift_part_ids':[{'id':part.id,'name':part.category_part_id.name,'qrcode':part.qrcode} for part in lift.lift_part_ids]
        }
        return json.dumps({"lift_info":lift_info})

    @http.route("/main/lift/public/bindcard", auth="user",csrf=False)
    def public_lift_bind_card(self,**kw):
        """
        公众号绑定页面绑定标识牌或者部位卡
        """
        lift = request.env["tyibs.base.lift"].sudo().search([("id", "=", kw['lift_id'])], limit=1)
        # card = request.env["tyibs.main.identification.card"].sudo().search([("qrcode", "=", kw['qrcode']),('install_state','=','uninstall')], limit=1)
        # if len(card) == 0:
        #     return json.dumps({"errcode":407,"errmessage":u"标识牌不符合绑定要求"})
        card = request.env["tyibs.main.identification.card"].sudo().search([("qrcode", "=", kw['qrcode'])], limit=1)
        if len(card) == 0:
            return json.dumps({"errcode":407,"errmessage":u"该标识牌未录入系统"})
        if card.install_state != 'uninstall':
            return json.dumps({"errcode":408,"errmessage":u"该标识牌已经绑定过了"})
        # 获取绑定人维保公司
        user_id = request.env["res.users"].sudo().search([("id", "=", request.session['uid'])], limit=1)
        maintenance_company_id = user_id.main_company_id.id if user_id.main_company_id else False
        card.write({
            'maintenance_company_id':maintenance_company_id,
            'install_state':'install',
            'lift_id':kw['lift_id'],
            'lift_part_id':kw['part_id'],
            'bind_time':datetime.datetime.utcnow()
        })
        # 更换电梯维保公司
        if maintenance_company_id and lift.maintenance_company_id.id != maintenance_company_id and card.card_type=='identification':
            lift.sudo().write({'maintenance_company_id':maintenance_company_id})
        return json.dumps({"errcode":0,"errmessage":u"绑定成功"})
    
    # 公众号的方法操作
    @http.route("/wechat/getjsconfig",auth="user",csrf=False)
    def get_wechat_js_config(self,**kw):
        """申请微信JS使用权限"""
        url = kw['url']
        timest = time.time()
        timestamp = int(timest)
        nonceStr = 'mainbind'
        app_id = request.env['ir.config_parameter'].get_param('tyibs.wechat.public.appid')
        secret = request.env['ir.config_parameter'].get_param('tyibs.wechat.public.secret')
        # 一小时刷一次判断是否过期
        wechat_date_token = request.env['ir.config_parameter'].get_param('tyibs.wechat.public.date.token')
        now_token =  str(datetime.datetime.now())[:13]
        signature =''
        ticket = request.env['ir.config_parameter'].get_param('tyibs.wechat.public.ticket')
        if now_token != wechat_date_token:
            # print u"ticket---过期"
            client = WeChatClient(app_id, secret)
            jsapi = WeChatJSAPI(client)
            ticket = jsapi.get_ticket()['ticket']
            request.env['ir.config_parameter'].sudo().set_param('tyibs.wechat.public.date.token',now_token)
            request.env['ir.config_parameter'].sudo().set_param('tyibs.wechat.public.token',client.access_token)
            request.env['ir.config_parameter'].sudo().set_param('tyibs.wechat.public.ticket',ticket)
            sign_str = "jsapi_ticket="+ticket+"&noncestr="+nonceStr+"&timestamp="+str(timestamp)+"&url="+url
            signature = hashlib.sha1(sign_str).hexdigest()
        else:
            # print u"ticket---还没有过期"
            sign_str = "jsapi_ticket="+ticket+"&noncestr="+nonceStr+"&timestamp="+str(timestamp)+"&url="+url
            signature = hashlib.sha1(sign_str).hexdigest()
        data = {"appId": app_id, "timestamp": timestamp, "nonceStr": nonceStr, "signature": signature,"ticket":ticket}
        return json.dumps(data)
    
    # 拍照上传
    @http.route('/main/lift/public/upimg',auth='user')
    def upDatePhoto(self,**kw):
        """微信上传电梯照片"""
        app_id = request.env['ir.config_parameter'].get_param('tyibs.wechat.public.appid')
        secret = request.env['ir.config_parameter'].get_param('tyibs.wechat.public.secret')
        token = request.env['ir.config_parameter'].get_param('tyibs.wechat.public.token')
        client = WeChatClient(app_id, secret,token)
        server_img = client.media.download(kw['server_id'])
        imagData = ""
        imagData = tools.image_resize_image_big(server_img.content.encode('base64'))
        lift = request.env["tyibs.base.lift"].sudo().search([("id", "=", kw['lift_id'])], limit=1)
        lift.sudo().write({'bind_image':imagData})
        return json.dumps({"err": 0})


    @http.route('/main/lineoperator/all',auth='user')
    def getAllLineOperator(self):
        """ 获取网络供应商列表 """
        line_operator_ids = request.env["tyibs.main.line.operator"].search([])
        return json.dumps([{'id':item.id,'name':item.name,'select':''} for item in line_operator_ids])

    @http.route('/main/bindlift/write',auth='user',csrf=False)
    def bindLiftWrite(self,**kw):
        """ 绑定标识牌中确认电梯信息 """
        lift = request.env["tyibs.base.lift"].sudo().search([("id", "=", kw['lift_id'])], limit=1)
        write_obj = {
            'ln':kw['ln'],
            'la':kw['la'],
            'gps_address':kw['gps_address'],
        }
        line_ids = json.loads(kw['line_operator_ids'])
        write_obj['line_operator_ids'] = [[6,False,[line_ids]]] if len(line_ids) else [[6,False,[]]]
        lift.sudo().write(write_obj)
        return json.dumps({'err':0})
